<%@ page import="java.util.*,merlin.beans.*,merlin.dao.*,merlin.managers.*,merlin.servlets.*,merlin.utils.*" errorPage="mr_errhandler.jsp" %>

<jsp:useBean id="autoFill" scope="session" class = "merlin.beans.AutoFillDetails"/>

<%!

	ApplicationResources resource = ApplicationResources.getInstance();

	String separatorString = resource.getProperty("separatorString");
	String separatorPattern = resource.getProperty("separatorPattern");

	public String getFormattedReportDetails(List lstReportNames){
		StringBuffer sbufReportDetails = new StringBuffer();

		StringBuffer tempBuffer = new StringBuffer();
		// change the array into uppercased "'" enclosed and comma separated
		// string which can be used in a SQL IN clause.
		for(int i=0;i<lstReportNames.size();i++){
			String strReportName = (String) lstReportNames.get(i);
			// clean the report name in case there are embedded ' characters which create problems in SQL queries.
			strReportName = strReportName.replaceAll("'","''");
			tempBuffer.append('\'').append(strReportName.substring(1).toUpperCase()).append('\'').append(',');
		}
		// remove the last ","
		tempBuffer.deleteCharAt(tempBuffer.length() - 1);

		String whereClause = "REPORT_TITLE IN (" + tempBuffer.toString() + ")";
		String orderBy = "REPORT_TITLE ASC";
		DbResultSet result = ReportTitlesManager.selectReportTitlesRecords(whereClause,orderBy);

		if(result != null && result.size() > 0){
  			int length = result.size();
  			for(int i=0;i< length - 1;i++){
  				ReportTitlesBean bean = (ReportTitlesBean)result.get(i);
      			sbufReportDetails.append(bean.getReportTitlesId()).append(separatorString).append(bean.getReportTitle()).append(separatorString);
  			}
			ReportTitlesBean bean = (ReportTitlesBean)result.get(length - 1);
   			sbufReportDetails.append(bean.getReportTitlesId()).append(separatorString).append(bean.getReportTitle());
  		}

		return sbufReportDetails.toString();
	}

%>

<%
	// This additional code is used to format the data that may come from the enquiries.jsp page.
	// The enquiries.jsp page sends the data in the form of checkboxes whose names are the report names.
	// Each report name starts with the '-' character and the report names are in Title case.
 	Enumeration names = request.getParameterNames();
 	List list = new LinkedList();
 	while(names.hasMoreElements()){
 		String name = (String)names.nextElement();
 		if(name.charAt(0) =='-'){
 			// This is a report name.
 			list.add(name.substring(0));
 		}
 	}
 	// put the data into the request attribute which is used later on for autofilling the list box.
 	if(list.size() > 0){
	 	String strReportNames = getFormattedReportDetails(list);
 		request.setAttribute("hidSelectedReports",strReportNames);
 	}

%>
<HTML>
<HEAD>
    <TITLE>Provide Contact Details</TITLE>
	<script>

		function isBlank(str){
			var len = str.length;
			if(len==0)return true;	// zero-length string
			for(i=0;i<len;i++){
				if(str.charAt(i) !=' ' && str.charAt(i) !='\n')return false; //some character is there
			}
			return true;
		}

		//validate the format of the e-mail address
		function isValidateEMailFormat(aEMailAddress){
			//Check for an email with a .com or .net extension
			var emailcom = /^[a-z][a-z_0-9\.]+@[a-z_0-9\.]+\.[a-z]{3}$/i
			//Check for an email with a .co.uk extension
			var emailcouk = /^[a-z][a-z0-9_\.]+@[a-z0-9_\.]+\.[a-z][a-z]\.[a-z][a-z]$/i
			var TheEMailAddress = new String(aEMailAddress);
			var tmpemail = aEMailAddress;
			var tmpamount = 0;
			var onechars = '';
			//validate the email format
			if ((TheEMailAddress.match(emailcom)) && (TheEMailAddress.match(emailcouk))) {
				return(false);
			};

			//ensure that the e-mail address contains 1 '@'
			for(var p=0; p < tmpemail.length; p++){
				onechars = tmpemail.charAt(p);
				if (onechars == '@')
					tmpamount = tmpamount + 1;
			}//for

			if (tmpamount != 1) {
				return(false);
			}

			return(true);
		}

		function doRemoveSelected(frm){
			var idx = frm.lstSelectedReports.selectedIndex;
			if(idx != -1){
				if(confirm("Remove selected report?")){
					frm.lstSelectedReports.remove(idx);
				}
			}
		}

		function doBack(frm){
			//return to the search page.
			var reportTitles ="";
			var lstLen = frm.lstSelectedReports.length;
			if(lstLen> 0){
   				for(i=0;i < lstLen - 1;i++){
					reportTitles += frm.lstSelectedReports.options[i].value + "<%= separatorString %>" + frm.lstSelectedReports.options[i].text + "<%= separatorString %>";
				}
				reportTitles += frm.lstSelectedReports.options[lstLen-1].value + "<%= separatorString %>" + frm.lstSelectedReports.options[lstLen-1].text;
			}
			frm.hidSelectedReports.value=reportTitles;

			//frm.action = '<%=request.getParameter("pageName")%>';
			frm.action="mr_searchReports.jsp";
			frm.submit();
		}

		function submitForm(frm){
			// validate the fields first.
			if(isBlank(frm.txtFirstName.value)){
				alert("Firstname is required");
				frm.txtFirstName.focus();
				return;
			}
			if(isBlank(frm.txtSurname.value)){
				alert("Surname is required");
				frm.txtSurname.focus();
				return;
			}
			if(isBlank(frm.txtCompanyName.value)){
				alert("CompanyName is required");
				frm.txtCompanyName.focus();
				return;
			}
			if(isBlank(frm.txtEMailAddress.value)){
				alert("EMail Address is required");
				frm.txtEMailAddress.focus();
				return;
			}
			if(! isValidateEMailFormat(frm.txtEMailAddress.value)){
				alert("EMail Address is not a valid one");
				frm.txtEMailAddress.focus();
				return;
			}
			if(isBlank(frm.txtTelephone.value)){
				alert("Telephone number is required");
				frm.txtTelephone.focus();
				return;
			}


			var reportTitles ="";
			var lstLen = frm.lstSelectedReports.length;
			if(lstLen> 0){
   				for(i=0;i < lstLen - 1;i++){
					reportTitles += frm.lstSelectedReports.options[i].value + "<%= separatorString %>" + frm.lstSelectedReports.options[i].text + "<%= separatorString %>";
				}
				reportTitles += frm.lstSelectedReports.options[lstLen-1].value + "<%= separatorString %>" + frm.lstSelectedReports.options[lstLen-1].text;
			}
			frm.hidSelectedReports.value=reportTitles;

			frm.action = "merlin";
			frm.mode.value="saveNewEnquiry";
			frm.submit();
		}
	</script>
</HEAD>
<BODY>
	<jsp:include page="mr_header.jsp"/>
	<p/>
	<table align="center" width="750px" border="0">
		<tr>
			<td colspan="2" align="center" style='color:white;height:23px;font: 11px verdana,arial, sans-serif ;background:url("mr_images/LongBars-orange750.jpg") no-repeat;' >
				<h4 style="vertical-align:middle">&nbsp;Your Details</h4>
			</td>
		</tr>
	</table>

	<table align="center" width="750px" cellpadding="0" cellspacing="0" style="font-family: Verdana, Helvetica, Arial, sans-serif;font-size: 11px;">
		<tbody>
		<tr>
			<td>
				<form name="frmContactDetails" method="post" action="merlin">

					<input type="hidden" name="mode" value="saveNewEnquiry">
					<input type="hidden" name="hidSelectedReports" value="">
					<input type="hidden" name="emailSubject" value='New Enquiry From <%=request.getParameter("emailFrom") %>'>

					Please provide your contact details completing all fields of information.<br>
					<table style="margin: 14px 0px;font-family: Verdana, Helvetica, Arial, sans-serif;font-size: 11px;" cellpadding="5" cellspacing="0" >
						<tbody>
						<tr>
							<td style="vertical-align: middle; width: 110px;">
								<span style="color: rgb(177, 115, 12);">*</span> First Name
							</td>
							<td>
								<input name="txtFirstName" type="text" value='<jsp:getProperty name="autoFill" property="txtFirstName"/>'>
							</td>
						</tr>
						<tr>
							<td style="vertical-align: middle;">
								<span style="color: rgb(177, 115, 12);">*</span> Surname
							</td>
							<td>
								<input name="txtSurname" type="text" value='<jsp:getProperty name="autoFill" property="txtSurname"/>'>
							</td>
						</tr>
						<tr>
							<td style="vertical-align: middle;">
								<span style="color: rgb(177, 115, 12);">*</span> Company
							</td>
							<td>
								<input name="txtCompanyName" type="text" value='<jsp:getProperty name="autoFill" property="txtCompanyName"/>'>
							</td>
						</tr>
						<tr>
							<td style="vertical-align: middle;">
								<span style="color: rgb(177, 115, 12);">*</span> Email Address
							</td>
							<td>
								<%
									// A complicated situation here :
									// The email address can come from either the user typing it or being retrieved
									// from the database for an existing user . So both validations will be checked,
									// with the user-filled email taking precedence.
									String emailAddress = (String)session.getAttribute("emailAddress");
									if(autoFill.getTxtEMailAddress() != null && autoFill.getTxtEMailAddress().length() > 0){
										emailAddress = autoFill.getTxtEMailAddress();
									}
									if(emailAddress == null) emailAddress = "";
								%>

								<input name="txtEMailAddress" type="text"  value='<%=emailAddress %>'>
							</td>
						</tr>
						<tr>
							<td style="vertical-align: middle;">
								<span style="color: rgb(177, 115, 12);">*</span> Telephone No.
							</td>
							<td>
								<input name="txtTelephone" type="text" value='<jsp:getProperty name="autoFill" property="txtTelephone"/>'>
							</td>
						</tr>
  						</tbody>
					</table>
  					We will provide order forms listing the companies contained in all your selected reports below. <em>(Click to select a report)</em><br>
					<select name="lstSelectedReports" style="margin: 7px 0px 0px;" size="5" multiple="multiple">
			  		<%
			  			// look for "hidSelectedReports" in both request.getAttribute() & request.getParameter()
			  			String selectedReports = request.getParameter("hidSelectedReports");
			  			if(selectedReports == null){
			  				selectedReports = (String) request.getAttribute("hidSelectedReports");
			  			}
			  			if(selectedReports != null && selectedReports.length() > 0){
					  		String[] array = selectedReports.split(separatorPattern);
					  		int tokens = array.length;
			  				for(int i=0;i<tokens - 1;i+=2){
					  			String reportNumber = array[i];
					  			String reportName = array[i+1];
			             		out.println("<option value=\"" + reportNumber + "\">" + reportName + "</option>");
					  		}
			        	}
			  		%>
					</select>
					<br><br>
					<input name="btnBack" class="input" value="Search More Reports" style="font-size: 11px; width: 130px;" onclick="doBack(this.form)" type="button">
					<input name="btnRemove" class="input" value="Remove Selected" style="font-size: 11px; width: 130px;" onclick="doRemoveSelected(this.form)" type="button">
					<input name="btnSend" class="input" value="Send Email to MSAL" style="font-size: 11px; width: 130px;" onclick="submitForm(this.form)" type="button">
				</form>
				</div>
			</td>
 		</tr>
		</tbody>
	</table>
	<jsp:include page="mr_footer.jsp"/>
	
	<!-- Start of StatCounter Code -->
<script type="text/javascript" language="javascript">
var sc_project=928985; 
var sc_invisible=1; 
var sc_partition=7; 
var sc_security="206963a7"; 
</script>

<script type="text/javascript" language="javascript" src="http://www.statcounter.com/counter/frames.js"></script><noscript><a href="http://www.statcounter.com/" target="_blank"><img  src="http://c8.statcounter.com/counter.php?sc_project=928985&amp;amp;java=0&amp;amp;security=206963a7&amp;amp;invisible=1" alt="hidden hit counter" border="0"></a> </noscript>
<!-- End of StatCounter Code -->
	
</BODY>
</HTML>